package pe.edutec.app.layer.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pe.edutec.app.domain.Empleado;
import pe.edutec.app.layer.service.LogonService;


@WebServlet({"/InicioController","/FinController"})
public class IngresoController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String alias = request.getServletPath();
		if(alias.equals("/InicioController")){
			inicioController(request,response);
		} 
	}

	

	private void inicioController(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String destino;
		try {
			// Datos
			String usuario = request.getParameter("usuario").toString();
			String clave = request.getParameter("clave").toString();
			// Validar
			LogonService service = new LogonService();
			Empleado emp = service.validar(usuario, clave);
			// Acceder a la sesion
			HttpSession session = request.getSession(true);
			session.setAttribute("empleado", emp);
			// Destino
			destino = "paginaPrincipal.jsp";
		} catch (Exception e) {
			request.setAttribute("error", e.getMessage());
			destino = "index.jsp";
		}
		RequestDispatcher rd = request.getRequestDispatcher(destino);
		rd.forward(request, response);
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String alias = request.getServletPath();
		if(alias.equals("/FinController")){
			finController(request,response);
		}
	}
	
	private void finController(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		session.invalidate();
		RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
		rd.forward(request, response);
	}

}
